<!-- src/components/dictItem/dictItem.vue -->
<template>
  <text :class="className">{{ dictText }}</text>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { dictCache } from '@/utils/dictCache'

// 定义组件属性
interface Props {
  dictCode: string
  value: string
  className?: string
}

const props = withDefaults(defineProps<Props>(), {
  className: '',
})

// 定义响应式数据
const dictText = ref<string>(props.value)

// 更新显示文本
const updateDictText = (dictData: any[]) => {
  const dictItem = dictData.find((item) => item.value === props.value)
  dictText.value = dictItem ? dictItem.text : props.value
}

// 获取字典数据
const fetchDictData = async () => {
  if (!props.dictCode) return

  try {
    const data = await dictCache.getDictItems(props.dictCode)
    updateDictText(data)
  } catch (error) {
    console.error(`获取字典数据失败: ${props.dictCode}`, error)
  }
}

// 监听属性变化
watch(
  () => [props.dictCode, props.value],
  () => {
    fetchDictData()
  },
  { immediate: true },
)
</script>
